import Footer from '@/components/Footer';
import { login, register } from '@/services/ant-design-pro/api';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { Alert, Tabs } from 'antd';
import React, { useState } from 'react';
import { history, useModel } from 'umi';

import styles from './login.less';
import { useForm } from 'antd/es/form/Form';

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);
const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.ResponseResult>({
    code: 0,
    data: null,
    message: '',
  });
  const [userRegisterState, setUserRegisterState] = useState<API.ResponseResult>({
    code: 0,
    data: null,
    message: '',
  });
  const [type, setType] = useState<string>('login');
  const { initialState, setInitialState } = useModel('@@initialState');
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };
  const [form] = useForm();
  const handleSubmit = async (values: API.RegisterParams) => {
    const fnc = type === 'login' ? login : register;
    const msg = await fnc({
      ...values,
    });
    if (msg.code !== 0) {
      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
      type === 'login' ? setUserLoginState(msg) : setUserRegisterState(msg);
      return;
    }
    await fetchUserInfo();
    if (type === 'login') {
      if (!history) return;
      const { query } = history.location;
      const { redirect } = query as {
        redirect: string;
      };
      history.push(redirect || '/');
    } else {
      setType('login');
      form.resetFields();
    }
  };
  const handleChange = (key: string) => {
    setType(key);
    form.resetFields();
    setUserLoginState({ code: 0, data: null, message: '' });
    setUserRegisterState({ code: 0, data: null, message: '' });
  };
  // @ts-ignore
  const { code, message } = type === 'login' ? userLoginState : userRegisterState;
  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          form={form}
          submitter={{
            searchConfig: {
              submitText: type === 'login' ? '登录' : '注册',
            },
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="Visual Decispace 智策空间"
          subTitle={'智能 BI 平台'}
          onFinish={async (values) => {
            await handleSubmit(values as API.RegisterParams);
          }}
        >
          <Tabs activeKey={type} onChange={handleChange}>
            <Tabs.TabPane key="login" tab={'LOGIN'} />
            <Tabs.TabPane key="register" tab={'REGISTER'} />
          </Tabs>

          {code !== 0 && type === 'login' && <LoginMessage content={message || '登录失败'} />}
          {type === 'login' && (
            <>
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'账号'}
                rules={[
                  {
                    required: true,
                    message: '账号是必填项',
                  },
                  {
                    pattern: /^[a-zA-Z0-9]{6,}$/,
                    message: '账号不能包含特殊字符且长度不少于6',
                  },
                ]}
              />
              <ProFormText.Password
                name="userPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项',
                  },
                  {
                    pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,10}$/,
                    message: '密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间',
                  },
                ]}
              />
            </>
          )}

          {code !== 0 && type === 'register' && <LoginMessage content={message || '注册失败'} />}
          {type === 'register' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                name="userAccount"
                placeholder={'账号'}
                rules={[
                  {
                    required: true,
                    message: '账号是必填项',
                  },
                  {
                    pattern: /^[a-zA-Z0-9]{6,}$/,
                    message: '账号不能包含特殊字符且长度不少于6',
                  },
                ]}
              />
              <ProFormText.Password
                name="userPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项',
                  },
                  {
                    pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,10}$/,
                    message: '密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间',
                  },
                ]}
              />
              <ProFormText.Password
                name="checkPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'确认密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项',
                  },
                  {
                    pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,10}$/,
                    message: '密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间',
                  },
                ]}
              />
            </>
          )}
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
export default Login;
